package edu.intprog.egreeting;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import edu.intprog.egreeting.basic.EgreetingBaseServlet;
/**
 * Servlet implementation class for Servlet: StartServlet
 *
 */
public class StartServlet extends EgreetingBaseServlet implements javax.servlet.Servlet {
	static final long serialVersionUID = 1L;
    public static final String seperator ="#@#";
    public static final String cookieName = "egreeting.user";
	/* (non-Java-doc)
	 * @see javax.servlet.http.HttpServlet#HttpServlet()
	 */
	public StartServlet() {
		super();
	}   	

	/* (non-Java-doc)
	 * @see javax.servlet.http.HttpServlet#service(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {			 
		// Go through all the cookies we have, looking for a faveColor.
		String  encodedDetails=new String();
		
		Cookie[] mySiteCookies = request.getCookies( );
		
		if (mySiteCookies!=null) {
			for (int i=0; i<mySiteCookies.length; i++) {
				Cookie c = mySiteCookies[i];
				if (c.getName( ).equals(cookieName)) {
					encodedDetails = c.getValue();
					break;
				}
			}
		}
		
		String []decodedDetails=loadFromCookie(encodedDetails);
		request.setAttribute("emailAddr", decodedDetails[0]);
		request.setAttribute("userPassword", decodedDetails[1]);
		String checkedState = (decodedDetails[0].length()>0)? "checked":"";
		request.setAttribute("checkedState", checkedState);
		
		getServletContext().getRequestDispatcher("/index.jsp").include(request, response);
	}  	

	/**
	 * generateCookie
	 * 
	 * encode the given email and password as a suited string fitted for a cookie
	 * 
	 * @param data - data to encode into a cookie string
	 * @return encoded string
	 */
	public static synchronized String generateCookie(String[] data) {
		String cookie = new String();
		
		for (int i=0;i<data.length;++i)
		{
			cookie = cookie + data[i] + seperator;
		}
		
		String encoded = new String();
		byte[] c_arr = cookie.getBytes();
		for (int i=0; i<cookie.length();i++)
		{
			int ch = c_arr[i];
			encoded = encoded + " " +Integer.toHexString(ch);
		}
		
		return encoded;
	}
	
	/**
	 * loadFromCookie
	 * 
	 * load the strings that are stored in the given encoded cookie string
	 * @param cookie - encoded cookie string
	 * @return decoded strings
	 */
	public static synchronized String[] loadFromCookie(String cookie) {
		String[] hexbits = cookie.split(" ");
		
		String decoded = new String();
		
		for (int i=0; i<hexbits.length;++i)
		{
			if (hexbits[i].length()>0) { 
				char ch = (char) Byte.parseByte(hexbits[i],16);
				decoded = decoded + ch;
			}
		}
		
		String[] data = decoded.split(seperator);
		if (data.length!=2)
		{
			data = new String[]{"",""};
		}
		return data;
	} 	  	    
}